from django.shortcuts import render
from common import response
import tushare as ts
from stock.models import *
import time

pro = ts.pro_api('7ea805c9f2f77d31c9f42f3755d08b62df238f628656aa006a6b0a95')
# ts.set_token('7ea805c9f2f77d31c9f42f3755d08b62df238f628656aa006a6b0a95')

# 股票列表
def basic(request):
    df = pro.query('stock_basic', fields='ts_code,symbol,name,area,industry,fullname,enname,market,curr_type,list_status,list_date,delist_date,is_hs')
    basics = []
    for r in df.index:
        row = df.iloc[r,:]
        have = Basic.objects.filter(ts_code=row['ts_code'])
        if not have.exists():
            b = Basic(ts_code=row['ts_code'],symbol=row['symbol'],name=row['name'],area=row['area'],industry=row['industry'],fullname=row['fullname'],enname=row['enname'],market=row['market'],curr_type=row['curr_type'],list_status=row['list_status'],list_date=row['list_date'],delist_date=row['delist_date'],is_hs=row['is_hs'])
            basics.append(b)
    Basic.objects.bulk_create(basics)
    return response.json_response('success')

# 交易日历
def cal(request):
    exchange = 'SSE'
    end_date = Cal.objects.filter(exchange=exchange).order_by('-cal_date')[0]
    df = pro.query('trade_cal', exchange=exchange, start_date=end_date.cal_date, fields='exchange,cal_date,is_open,pretrade_date')
    cals = []
    for r in df.index:
        row = df.iloc[r,:]
        have = Cal.objects.filter(exchange=row['exchange'], cal_date=row['cal_date'])
        if not have.exists():
            b = Cal(exchange=row['exchange'],cal_date=row['cal_date'],is_open=row['is_open'],pretrade_date=row['pretrade_date'])
            cals.append(b)
    Cal.objects.bulk_create(cals)
    return response.json_response('success')

# 日线行情
def daily(request):
    begin_date = Daily.objects.order_by('-trade_date')[0].trade_date
    end_date = time.strftime('%Y%m%d')
    dates = Cal.objects.filter(cal_date__gt=begin_date, cal_date__lte=end_date, is_open=1).order_by('cal_date')
    for date in dates:
        dailies = []
        df = pro.query('daily', trade_date=date.cal_date, fields='ts_code,trade_date,open,high,low,close,pre_close,change,pct_chg,vol,amount')
        df.fillna(value=0.0, inplace=True)
        for r in df.index:
            row = df.iloc[r,:]
            b = Daily(ts_code=row['ts_code'],trade_date=row['trade_date'],open=row['open'],high=row['high'],low=row['low'],close=row['close'],pre_close=row['pre_close'],change=row['change'],pct_chg=row['pct_chg'],vol=row['vol'],amount=row['amount'])
            dailies.append(b)
        Daily.objects.bulk_create(dailies)
    return response.json_response('success')

# 复权因子
def adj_factor(request):
    begin_date =  AdjFactor.objects.order_by('-trade_date')[0].trade_date
    end_date = time.strftime('%Y%m%d')
    dates = Cal.objects.filter(cal_date__gt=begin_date, cal_date__lte=end_date, is_open=1).order_by('cal_date')
    for date in dates:
        dailies = []
        df = pro.query('adj_factor',  trade_date=date.cal_date, fields='ts_code,trade_date,adj_factor')
        df.fillna(value=0.0, inplace=True)
        for r in df.index:
            row = df.iloc[r,:]
            b = AdjFactor(ts_code=row['ts_code'],trade_date=row['trade_date'],adj_factor=row['adj_factor'])
            dailies.append(b)
        AdjFactor.objects.bulk_create(dailies)
    return response.json_response('success')

# 沪深港通资金流向
# def moneyflow_hsgt(request):
#     begin_date = '19901219'
#     end_date = time.strftime('%Y%m%d')
#     dates = Cal.objects.filter(cal_date__gt=begin_date, cal_date__lte=end_date, is_open=1).order_by('cal_date')
#     for date in dates:
#         dailies = []
#         df = pro.query('moneyflow_hsgt',  trade_date=date.cal_date, fields='trade_date,ggt_ss,ggt_sz,hgt,sgt,north_money,south_money')
#         df.fillna(value=0.0, inplace=True)
#         for r in df.index:
#             row = df.iloc[r,:]
#             b = Moneyflow_hsgt(trade_date=row['trade_date'],ggt_ss=row['ggt_ss'],ggt_sz=row['ggt_sz'],hgt=row['hgt'],sgt=row['sgt'],north_money=row['north_money'],south_money=row['south_money'])
#             dailies.append(b)
#         Moneyflow_hsgt.objects.bulk_create(dailies)
#     return response.json_response('success')
#
# # 沪深港通资金流向
# def hsgt_top10(request):
#     begin_date = '19901219'
#     end_date = time.strftime('%Y%m%d')
#     dates = Cal.objects.filter(cal_date__gt=begin_date, cal_date__lte=end_date, is_open=1).order_by('cal_date')
#     for date in dates:
#         dailies = []
#         df = pro.query('hsgt_top10',  trade_date=date.cal_date, fields='trade_date,ts_code,name,close,change,rank,market_type,amount,net_amount,buy,sell')
#         df.fillna(value=0.0, inplace=True)
#         for r in df.index:
#             row = df.iloc[r,:]
#             b = Hsgt_top10(trade_date=row['trade_date'],ts_code=row['ts_code'],name=row['name'],close=row['close'],change=row['change'],rank=row['rank'],market_type=row['market_type'],amount=row['amount'],net_amount=row['net_amount'],buy=row['buy'],sell=row['sell'])
#             dailies.append(b)
#         Hsgt_top10.objects.bulk_create(dailies)
#     return response.json_response('success')
#
#
# # 沪深港股通持股明细
# def hk_hold(request):
#     begin_date = '19901219'
#     end_date = time.strftime('%Y%m%d')
#     dates = Cal.objects.filter(cal_date__gt=begin_date, cal_date__lte=end_date, is_open=1).order_by('cal_date')
#     for date in dates:
#         dailies = []
#         df = pro.query('hk_hold',  trade_date=date.cal_date, fields='code,trade_date,ts_code,name,vol,ratio,exchange')
#         df.fillna(value=0.0, inplace=True)
#         for r in df.index:
#             row = df.iloc[r,:]
#             b = Hk_hold(code=row['code'],trade_date=row['trade_date'],ts_code=row['ts_code'],name=row['name'],vol=row['vol'],ratio=row['ratio'],exchange=row['exchange'])
#             dailies.append(b)
#         Hk_hold.objects.bulk_create(dailies)
#     return response.json_response('success')
#
# def moneyflow(reques):
#     df = pro.moneyflow(ts_code='002149.SZ', start_date='20190115', end_date='20190315')
#     print(df)

# 股票列表
def performance(request):
    df = ts.get_stock_basics()
    basics = []
    for code in df.index:
        row = df.loc[code,:]
        have = Performance.objects.filter(code=code)
        if not have.exists():
            b = Performance(code=code,name=row['name'],reserved_per_share=row['reservedPerShare'],esp=row['esp'],bvps=row['bvps'],perundp=row['perundp'])
            basics.append(b)
    Performance.objects.bulk_create(basics)
    return response.json_response('success')

# 股票列表
def report_data(request):
    for year in [2020]:
        for quarter in [1,2,3]:
            df = ts.get_report_data(year,quarter)
            df.fillna(value=0.0, inplace=True)
            basics = []
            for code in df.index:
                row = df.loc[code,:]
                row['report_date'] = str(year) + '-' + row['report_date']
                # have = Report_data.objects.filter(code=code,report_date=row['report_date'])
                # if not have.exists():
                b = Report_data(code=row['code'],name=row['name'],esp=row['eps'],eps_yoy=row['eps_yoy'],bvps=row['bvps'],roe=row['roe'],epcf=row['epcf'],net_profits=row['net_profits'],profits_yoy=row['profits_yoy'],distrib=row['distrib'],report_date=row['report_date'],year=year,quarter=quarter)
                basics.append(b)
            Report_data.objects.bulk_create(basics)
    return response.json_response('success')

# 估计股票价值
# def estimate(request):

# python解析json
# http://webapi.cninfo.com.cn/#/thematicStatistics 用safari打开
def to_list(request):
    import json
    import os
    for date in ['2016-1','2016-2','2016-3','2016-4','2017-1','2017-2','2017-3','2017-4','2018-1','2018-2','2018-3','2018-4','2019-1','2019-2','2019-3','2019-4','2020-1','2020-2','2020-3','2020-4','2021-1','2021-2','2021-3']:
        with open(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/json/' + date, 'r', encoding='utf-8') as f:
            dic = json.load(f)
            basics = []
            for row in dic['records']:
                b = Main_indicators(code=row['SECCODE'], name=row['SECNAME'], eps=row['F002N'],
                                bvps=row['F003N'], roe=row['F004N'], epcf=row['F005N'], operation_revenue=row['F006N'],
                                operating_costs=row['F007N'], profit=row['F008N'], net_profit_to_parent=row['F009N'], gross_profit_rate=row['F010N'],
                                    operating_profit_ratio=row['F011N'], report_date=row['F001D'],)
                basics.append(b)
            Main_indicators.objects.bulk_create(basics)
    return response.json_response('success')